import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { getInfo, logout } from '@/api/login'
import { login} from '@/api/account'
import { ACCESS_TOKEN, LOGIN_ID } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import {findAccount} from '@/api/account'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.data
          storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
		  storage.set(LOGIN_ID, result.account.id)
          commit('SET_TOKEN', result.token)
		  commit('SET_NAME', {name:result.account.name,welcome:'欢迎回来'})
		  commit('SET_AVATAR', result.account.avatar)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
		findAccount(storage.get(LOGIN_ID)).then(res => {
			let role = []
			if(res.data.role){
				role = [res.data.role.code]
			}else{
				role = ['empty']
			}
			commit('SET_ROLES', role)
			commit('SET_INFO', res.data)
			resolve(role)
		}).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
		  storage.remove(LOGIN_ID)
          resolve()
      })
    }

  }
}

export default user
